<template>
  <div class="maintenance-plan-list-container">
    <el-card shadow="never" class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form" label-width="90px">
        <el-form-item label="计划名称">
          <el-input v-model="searchForm.planName" placeholder="计划名称" clearable />
        </el-form-item>
        <el-form-item label="计划类型">
          <el-select v-model="searchForm.planType" placeholder="请选择" clearable>
            <el-option label="预防性点检" value="预防性点检" />
            <el-option label="预防性保养" value="预防性保养" />
            <el-option label="润滑维护" value="润滑维护" />
            <el-option label="维修计划" value="维修计划" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划负责人">
          <el-select
            v-model="searchForm.responsibleUserId"
            placeholder="请选择"
            clearable
            filterable
          >
            <el-option
              v-for="user in maintenanceUsers"
              :key="user.userId"
              :label="user.userName"
              :value="user.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="计划状态">
          <el-select v-model="searchForm.status" placeholder="请选择" clearable>
            <el-option label="草稿" value="草稿" />
            <el-option label="已发布" value="已发布" />
            <el-option label="已过期" value="已过期" />
            <el-option label="已暂停" value="已暂停" />
          </el-select>
        </el-form-item>
        <el-form-item label="计划日期">
          <el-date-picker
            v-model="searchForm.planDateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 280px"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleResetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never" class="table-card">
      <div class="table-header">
        <el-button type="primary" @click="handleCreatePlan">新增维护计划</el-button>
        <el-button type="danger" :disabled="selectedPlans.length === 0" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <el-table
        :data="planList"
        v-loading="loading"
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="planId" label="计划ID" width="90" />
        <el-table-column prop="planName" label="计划名称" min-width="180" show-overflow-tooltip />
        <el-table-column prop="planType" label="计划类型" width="120" />
        <el-table-column prop="responsibleUserName" label="负责人" width="100" />
        <el-table-column label="关联设备" min-width="180" show-overflow-tooltip>
          <template #default="{ row }">
            <el-tag v-for="name in row.associatedDeviceNames" :key="name" size="small" style="margin-right: 5px; margin-bottom: 5px;">
              {{ name }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="计划周期" width="120">
            <template #default="{ row }">
                <span v-if="row.repeatCycle && row.repeatCycle.type !== 'none'">
                    {{ formatRepeatCycle(row.repeatCycle) }}
                </span>
                <span v-else>不重复</span>
            </template>
        </el-table-column>
        <el-table-column label="计划日期范围" width="200">
          <template #default="{ row }">
            {{ formatTime(row.planStartDate, 'date') }}<br/>至<br/>{{ formatTime(row.planEndDate, 'date') }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">{{ row.status }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="160" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button type="warning" link size="small" @click="handleEditPlan(row)">编辑</el-button>
            <el-button
                type="success"
                link
                size="small"
                @click="handlePublishPlan(row)"
                :disabled="row.status !== '草稿'"
            >发布</el-button>
            <el-button type="danger" link size="small" @click="handleDeletePlan(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :small="false"
        :disabled="loading"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑维护计划弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑维护计划' : '新增维护计划'"
      width="850px"
      :before-close="handleCloseDialog"
    >
      <el-form
        :model="planForm"
        :rules="planFormRules"
        ref="planFormRef"
        label-width="120px"
      >
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="计划名称" prop="planName">
              <el-input v-model="planForm.planName" placeholder="请输入计划名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计划类型" prop="planType">
              <el-select v-model="planForm.planType" placeholder="请选择计划类型" style="width: 100%">
                <el-option label="预防性点检" value="预防性点检" />
                <el-option label="预防性保养" value="预防性保养" />
                <el-option label="润滑维护" value="润滑维护" />
                <el-option label="维修计划" value="维修计划" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="计划描述" prop="description">
          <el-input
            type="textarea"
            v-model="planForm.description"
            :rows="3"
            placeholder="请输入计划详细描述"
          />
        </el-form-item>

        <el-form-item label="关联设备" prop="associatedDeviceIds">
          <el-select
            v-model="planForm.associatedDeviceIds"
            multiple
            filterable
            placeholder="请选择关联设备 (可多选)"
            style="width: 100%;"
          >
            <el-option
              v-for="item in allDevices"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-row :gutter="20">
            <el-col :span="12">
                <el-form-item label="计划负责人" prop="responsibleUserId">
                    <el-select
                        v-model="planForm.responsibleUserId"
                        placeholder="请选择计划负责人"
                        filterable
                        clearable
                        style="width: 100%;"
                    >
                        <el-option
                            v-for="user in maintenanceUsers"
                            :key="user.userId"
                            :label="user.userName"
                            :value="user.userId"
                        />
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="计划起始日期" prop="planStartDate">
                    <el-date-picker
                        v-model="planForm.planStartDate"
                        type="date"
                        placeholder="选择计划起始日期"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        style="width: 100%"
                    />
                </el-form-item>
            </el-col>
        </el-row>
        <el-form-item label="计划结束日期" prop="planEndDate">
            <el-date-picker
                v-model="planForm.planEndDate"
                type="date"
                placeholder="选择计划结束日期"
                value-format="YYYY-MM-DD HH:mm:ss"
                style="width: 100%"
            />
        </el-form-item>

        <el-form-item label="重复周期" prop="repeatCycle">
          <RepeatCycleSelector v-model="planForm.repeatCycle" />
        </el-form-item>

      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleCloseDialog">取消</el-button>
          <el-button type="primary" @click="handleSubmitForm" :loading="formSubmitting">
            {{ isEdit ? '保存修改' : '新增计划' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import {
  getPlanList,
  addPlan,
  updatePlan,
  deletePlan,
  publishPlan,
  getMaintenanceUsers // 也用于计划负责人
} from '@/stores/maintenance';
import { getAllDevices } from '@/stores/device'; // 用于设备选择器
import RepeatCycleSelector from '@/components/RepeatCycleSelector.vue';
import { format } from 'date-fns';

// --- 搜索表单相关 ---
const searchForm = reactive({
  planName: '',
  planType: '',
  responsibleUserId: null,
  status: '',
  planDateRange: [], // 日期范围 [start, end]
});

const handleSearch = () => {
  pagination.page = 1;
  fetchPlanList();
};

const handleResetSearch = () => {
  searchForm.planName = '';
  searchForm.planType = '';
  searchForm.responsibleUserId = null;
  searchForm.status = '';
  searchForm.planDateRange = [];
  handleSearch();
};

// --- 表格数据相关 ---
const planList = ref([]);
const loading = ref(false);
const selectedPlans = ref([]);

const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0,
});

// 所有设备列表
const allDevices = ref([]);
const fetchAllDevices = async () => {
  try {
    // 确保从 @/api/device 获取设备列表
    const res = await getAllDevices();
    if (res.code === 200) {
      allDevices.value = res.data;
    } else {
      ElMessage.error(res.message || '获取设备列表失败');
    }
  } catch (error) {
    ElMessage.error('请求所有设备列表异常');
    console.error(error);
  }
};

// 所有维修人员列表 (用于计划负责人选择)
const maintenanceUsers = ref([]);
const fetchMaintenanceUsers = async () => {
  try {
    const res = await getMaintenanceUsers();
    if (res.code === 200) {
      maintenanceUsers.value = res.data;
    } else {
      ElMessage.error(res.message || '获取维修人员列表失败');
    }
  } catch (error) {
    ElMessage.error('请求维修人员列表异常');
    console.error(error);
  }
};

const fetchPlanList = async () => {
  loading.value = true;
  try {
    const params = {
      ...searchForm,
      planDateRange: searchForm.planDateRange && searchForm.planDateRange.length === 2
                       ? searchForm.planDateRange : undefined,
      page: pagination.page,
      pageSize: pagination.pageSize,
    };
    const res = await getPlanList(params);
    if (res.code === 200) {
      planList.value = res.data.list; // 假设API已返回associatedDeviceNames
      pagination.total = res.data.total;
    } else {
      ElMessage.error(res.message || '获取维护计划列表失败');
    }
  } catch (error) {
    ElMessage.error('请求维护计划列表异常');
    console.error(error);
  } finally {
    loading.value = false;
  }
};

onMounted(() => {
  fetchAllDevices();
  fetchMaintenanceUsers().then(() => {
    fetchPlanList();
  });
});

const handleSelectionChange = (val) => {
  selectedPlans.value = val;
};

const getStatusTagType = (status) => {
  switch (status) {
    case '草稿': return 'info';
    case '已发布': return 'success';
    case '已过期': return 'warning';
    case '已暂停': return 'danger';
    default: return '';
  }
};

const formatTime = (timeStr, type = 'datetime') => {
    if (!timeStr) return '';
    try {
        if (type === 'date') {
            return format(new Date(timeStr), 'yyyy-MM-dd');
        }
        return format(new Date(timeStr), 'yyyy-MM-dd HH:mm');
    } catch (e) {
        return timeStr;
    }
};

const formatRepeatCycle = (cycle) => {
    if (!cycle || cycle.type === 'none') return '不重复';
    let str = `每${cycle.value}个`;
    switch (cycle.type) {
        case 'daily': return `${str}天`;
        case 'weekly':
            const days = cycle.dayOfWeek.map(d => ['日', '一', '二', '三', '四', '五', '六'][d]).join('/');
            return `${str}周的周${days}`;
        case 'monthly': return `${str}月${cycle.dayOfMonth}日`;
        case 'quarterly':
            const monthOffsetMap = { 0: '一', 1: '二', 2: '三' };
            return `${str}季度第${monthOffsetMap[cycle.monthOffset]}月${cycle.dayOfMonth}日`;
        case 'yearly': return `${str}年${cycle.month}月${cycle.dayOfMonth}日`;
        default: return '未知周期';
    }
};


// --- 分页相关 ---
const handleSizeChange = (val) => {
  pagination.pageSize = val;
  fetchPlanList();
};

const handleCurrentChange = (val) => {
  pagination.page = val;
  fetchPlanList();
};

// --- 新增/编辑弹窗相关 ---
const dialogVisible = ref(false);
const isEdit = ref(false);
const planFormRef = ref(null);
const formSubmitting = ref(false);
const planForm = reactive({
  planId: null,
  planName: '',
  planType: '预防性点检',
  description: '',
  associatedDeviceIds: [], // 存储设备ID数组
  planStartDate: '',
  planEndDate: '',
  responsibleUserId: null,
  repeatCycle: { type: 'none' }, // 默认不重复
});

// 表单校验规则
const planFormRules = {
  planName: [{ required: true, message: '请输入计划名称', trigger: 'blur' }],
  planType: [{ required: true, message: '请选择计划类型', trigger: 'change' }],
  description: [{ required: true, message: '请输入计划描述', trigger: 'blur' }],
  associatedDeviceIds: [{ type: 'array', required: true, message: '请选择关联设备', trigger: 'change', min: 1 }],
  responsibleUserId: [{ required: true, message: '请选择计划负责人', trigger: 'change' }],
  planStartDate: [{ required: true, message: '请选择计划起始日期', trigger: 'change' }],
  planEndDate: [
    { required: true, message: '请选择计划结束日期', trigger: 'change' },
    {
      validator: (rule, value, callback) => {
        if (value && planForm.planStartDate && new Date(value) < new Date(planForm.planStartDate)) {
          callback(new Error('计划结束日期不能早于起始日期'));
        } else {
          callback();
        }
      },
      trigger: 'change',
    },
  ],
  repeatCycle: [{
      validator: (rule, value, callback) => {
        if (value.type !== 'none') {
            // 对重复周期的内部字段进行更细致的校验，例如 weekly 必须选 dayOfWeek
            if (value.type === 'weekly' && (!value.dayOfWeek || value.dayOfWeek.length === 0)) {
                callback(new Error('每周重复需要选择星期几'));
            } else if ((value.type === 'monthly' || value.type === 'quarterly' || value.type === 'yearly') && !value.dayOfMonth) {
                callback(new Error('每月/季度/每年重复需要选择日期'));
            } else {
                callback();
            }
        }
        callback();
      },
      trigger: ['change', 'blur'],
      deep: true, // 深度监听对象内部的变化
    },
  ],
};

const handleCreatePlan = () => {
  isEdit.value = false;
  resetForm();
  dialogVisible.value = true;
};

const handleEditPlan = (row) => {
  isEdit.value = true;
  Object.assign(planForm, row);
  // 对于 repeatCycle，需要确保是一个新对象，否则直接传入会导致子组件修改父组件的数据
  planForm.repeatCycle = { ...row.repeatCycle };
  dialogVisible.value = true;
};

const handleSubmitForm = async () => {
  if (!planFormRef.value) return;
  const valid = await planFormRef.value.validate();
  if (!valid) {
    ElMessage.warning('请检查表单填写是否完整正确');
    return;
  }

  formSubmitting.value = true;
  try {
    let res;
    // 提交前进行深拷贝，防止响应式对象直接被修改
    const dataToSend = JSON.parse(JSON.stringify(planForm));

    if (isEdit.value) {
      if (!dataToSend.planId) throw new Error('编辑ID不存在');
      res = await updatePlan(dataToSend);
    } else {
      res = await addPlan(dataToSend);
    }

    if (res.code === 200) {
      ElMessage.success(`${isEdit.value ? '保存' : '新增'}计划成功`);
      dialogVisible.value = false;
      fetchPlanList(); // 刷新列表
    } else {
      ElMessage.error(res.message || `${isEdit.value ? '保存' : '新增'}计划失败`);
    }
  } catch (error) {
    ElMessage.error(`请求失败: ${error.message || '未知错误'}`);
    console.error(error);
  } finally {
    formSubmitting.value = false;
  }
};

const handleCloseDialog = () => {
  dialogVisible.value = false;
  resetForm();
  planFormRef.value?.resetFields();
};

const resetForm = () => {
  planForm.planId = null;
  planForm.planName = '';
  planForm.planType = '预防性点检';
  planForm.description = '';
  planForm.associatedDeviceIds = [];
  planForm.planStartDate = '';
  planForm.planEndDate = '';
  planForm.responsibleUserId = null;
  planForm.repeatCycle = { type: 'none' };
};


// --- 删除操作 ---
const handleDeletePlan = async (row) => {
  await ElMessageBox.confirm(`确定要删除计划 "${row.planName}" (ID: ${row.planId}) 吗？此操作不可恢复。`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const res = await deletePlan(row.planId);
        if (res.code === 200) {
          ElMessage.success('删除成功');
          fetchPlanList();
        } else {
          ElMessage.error(res.message || '删除失败');
        }
      } catch (error) {
        ElMessage.error(`请求失败: ${error.message || '未知错误'}`);
        console.error(error);
      }
    })
    .catch(() => {
      ElMessage.info('已取消删除');
    });
};

const handleBatchDelete = async () => {
  if (selectedPlans.value.length === 0) {
    ElMessage.warning('请选择要删除的计划');
    return;
  }
  const planNames = selectedPlans.value.map(p => p.planName).join('，');
  await ElMessageBox.confirm(`确定要删除选中的 ${selectedPlans.value.length} 条维护计划：${planNames} 吗？`, '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(async () => {
      try {
        const deletePromises = selectedPlans.value.map(p => deletePlan(p.planId));
        await Promise.all(deletePromises);
        ElMessage.success('批量删除成功');
        fetchPlanList();
        selectedPlans.value = [];
      } catch (error) {
        ElMessage.error(`批量删除失败: ${error.message || '未知错误'}`);
        console.error(error);
      }
    })
    .catch(() => {
      ElMessage.info('已取消批量删除');
    });
};

// --- 发布计划 ---
const handlePublishPlan = async (row) => {
    await ElMessageBox.confirm(`确定要发布计划 "${row.planName}" 吗？发布后计划将生效并可能自动生成任务。`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'info',
    })
    .then(async () => {
        try {
            const res = await publishPlan(row.planId);
            if (res.code === 200) {
                ElMessage.success('计划发布成功！');
                fetchPlanList();
            } else {
                ElMessage.error(res.message || '计划发布失败！');
            }
        } catch (error) {
            ElMessage.error(`请求失败: ${error.message || '未知错误'}`);
            console.error(error);
        }
    })
    .catch(() => {
        ElMessage.info('已取消发布');
    });
};
</script>

<style scoped>
.maintenance-plan-list-container {
  padding: 20px;
  background-color: var(--el-bg-color-page);
}

.search-card,
.table-card {
  margin-bottom: 20px;
}

.search-form .el-form-item {
  margin-bottom: 18px;
}

.table-header {
  display: flex;
  justify-content: flex-start;
  margin-bottom: 15px;
}

.table-header .el-button {
  margin-right: 10px;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>
